<?php

namespace Modules\Car\Http\Controllers\Api;


use App\Helpers\Constant;
use App\Helpers\NewBaseData;
use App\Helpers\ResponseData;
use App\Helpers\Utils;
use App\Models\Car;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\Customer;
use Modules\Car\Entities\Illegal;
use Modules\Car\Entities\Maintenance;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Entities\Service;
use Modules\Manager\Entities\Department;
use Illuminate\Support\Facades\Cache;
use App\Models\Car\Reimburse;
use App\Models\Car\ExternalTransfer;
use App\Models\User\BlackList;
use App\Models\InsureLogs;
//首页
class HomeController extends Controller
{
    use ResponseData,Utils;
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $user = $request->user();
        //待租车车辆
        $waitting_lease = Cache::remember('waitting_lease',30, function () {
            return RecognizeDrivingLicense::query()
                ->whereNull('deleted_at')
                ->where('is_used',0)
                ->where('status','!=','-1')
                ->count();
        });
        //小程序待确认
        // $waitting_confirm = Cache::remember('waitting_confirm',30, function () {
        //     return CarOrder::query()->whereIn('status',[0,1])->count();
        // });
        // 待维修车辆
        // $waitting_service_num = Cache::remember('waitting_service',30, function () {
        //     return $number+$serNum;
        // });
        //待处理违章
        // $waitting_illegals_num = Cache::remember('waitting_illegals',30, function () {
        //     return Illegal::query()->where('type',0)->count();
        // });
        $illegals_num1 = Cache::remember('illegals_num1',30, function () {
            return Illegal::query()->where('type',0)->count();
        });
        $illegals_num2 = Cache::remember('illegals_num2',30, function () {
            return Illegal::query()->where('type',1)->count();
        });
        $illegals_num3 = Cache::remember('illegals_num3',30, function () {
            return Illegal::query()->where('type',3)->count();
        });
        $illegals_num4 = Cache::remember('illegals_num4',30, function () {
            return Illegal::query()->where('type',2)->count();
        });
        //待维保
        $waitting_servicing_num = Cache::remember('waitting_servicing_num',30, function () {
            // 待大保养
            $big_serving = DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_spark_plug_mileage-spark_plug_mileage) <= ?',[5000])->count();
            // 待保养
            $number = DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_kilo_mileage-total_mileage) <= ?',[1000])->count();
            // 待维修
            $serNum =  Service::query()->where('status',2)->count();
            return $big_serving+$number+$serNum;
        });

        // $test['待大保养'] = DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_spark_plug_mileage-spark_plug_mileage) <= ?',[5000])->count();
        // $test['待保养'] = DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_kilo_mileage-total_mileage) <= ?',[1000])->count();
        // $test['待维修'] = Service::query()->where('status',2)->count();

        // 维保中
        $is_servincing_num = Cache::remember('is_servincing_num',30, function () {
            // 历史保养
            //$history_sercice = Maintenance::query()->where('id','>',0)->count();
            // 维保中
            $serving =  Service::query()->where('status',3)->count();
            return $serving;
        });
        // 维保管理
        $service_manage = Cache::remember('service_manage',30, function () {
            // 历史维修
            $history =  Service::query()->where('status',4)->count();
            // 历史保养
            $history_sercice = Maintenance::query()->where('id','>',0)->count();
            return $history_sercice+$history;
        });

        //已收车辆
        $is_over= CarOrder::query()
            ->where('status',6)
            ->where('process_status',3)
            //->where('department',$user->id)
            ->count();
        //今日收车
        $waitting_return = CarOrder::query()
            ->whereBetween('pre_return_time',[Carbon::today(),Carbon::tomorrow()])
            ->where('status',5)
            ->count();
        //逾期
        $over_time_return = CarOrder::query()
            ->where('pre_return_time','<',now())
            ->where('status',5)
            ->count();
        // 在租车辆
        $leased = RecognizeDrivingLicense::query()->whereNull('deleted_at')->where('is_used',1)->count();

        //预订单
        $perparatory = CarOrder::query()
            ->where('status',Constant::ORDER_IS_CONFIRM)
            ->count();
        // 店长数据
        if($user->post_id==2){
            //小程序待确认
            $waitting_confirm = CarOrder::query()->where('department',$user->department_id)->whereIn('status',[0,1])->count();
            // 历史订单
            $history_order = CarOrder::query()->where('status',6)->where('process_status',6)->where('department',$user->department_id)->count();
            // 待排车
            $waiting_car = CarOrder::query()
            ->where('status',Constant::ORDER_IS_SENDORDER)
            ->where('department',$user->department_id)
            ->count();
            //待签署
            $waiting_sign = CarOrder::query()
            ->where('status',5)
            ->whereIn('is_sign_contract',[1,2])
            ->where('department',$user->department_id)
            ->count();
            //用车中
            $used_car = CarOrder::query()
            ->where('status',5)
            ->where('is_sign_contract',3)
            ->where('is_send_return_order','!=',2)
            ->where('department',$user->department_id)
            ->count();
            //取回中
            $returning_car = CarOrder::query()
            ->where('status',5)
            ->where('is_sign_contract',3)
            ->where('return_employer_id','!=',0)
            ->where('department',$user->department_id)
            ->count();
            //待结算订单
            $waitting_settle = CarOrder::query()->where('status',6)->where('process_status',3)->where('department',$user->department_id)->count();
            //已取消订单
            $cancel_order = CarOrder::query()->whereIn('status',[-1,-2,-3])->where('department',$user->department_id)->count();
            //在租车车辆
            // $leased = CarOrder::query()->where('status',5)
            // ->where('department',$user->department_id)
            // ->count();
            //未结清
            $waitting_account = CarOrder::query()
                ->where('status',6)
                ->where(function($query){
                    $query->whereNotNull('unpaid')
                        ->orWhere('violation_unsettle')
                        ->orWhere('deposit_unsettle');
                })
                ->whereIn('process_status',[4,5])
                ->where('department',$user->department_id)
                ->count();
            // 租金未结清
            $unpaid_zj = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('department',$user->department_id)
            ->where('unpaid','>',0)
            ->count();
            // 押金未结清
            $unpaid_yj = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('department',$user->department_id)
            ->where('unpaid_yj','>',0)
            ->count();
            // 违章未结清
            $unpaid_wz = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('department',$user->department_id)
            ->where('unpaid_wz','>',0)
            ->count();
            // 事故未结清
            $unpaid_sg = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('department',$user->department_id)
            ->where('unpaid_sg','>',0)
            ->count();
            // $zdCount = 0;
            // $tuanCount = 0;
            // $bcCount = 0;
            // $lqCount = 0;
            // if($user->department_id==1){
            //     $zdCount = $this->cuctomer(1);
            // }
            // if($user->department_id==2){
            //     $tuanCount = $this->cuctomer(2);
            // }
            // if($user->department_id==3){
            //     $bcCount = $this->cuctomer(3);
            // }
            // if($user->department_id==4){
            //     $lqCount = $this->cuctomer(4);
            // }
            //待送达
            $arravite = $this->carProccess(1,$user,1);
            //待取回
            $refund = $this->carProccess(2,$user,1);
            // 报销审核
            $reimburse_count = Reimburse::query()->where('status',1)->where('is_month',1)->where('department',$user->department_id)->count();
            // 外调车订单
            $departmentitem = Department::query()->where('id',$user->department_id)->first();
            if($departmentitem){
                $wd_order = ExternalTransfer::query()->where('department',$departmentitem->name)->count();
            }
            // 黑名单数量
            // $hmd_num = BlackList::query()->where('department_id',$user->department_id)->whereNull('deleted_at')->count();
        }else{
            //小程序待确认
            $waitting_confirm = CarOrder::query()->whereIn('status',[0,1])->count();
            //待排车
            $waiting_car = CarOrder::query()
            ->where('status',Constant::ORDER_IS_SENDORDER)
            ->count();
            //待签署
            $waiting_sign = CarOrder::query()
            ->where('status',5)
            ->whereIn('is_sign_contract',[1,2])
            ->count();
            //用车中
            $used_car = CarOrder::query()
            ->where('status',5)
            ->where('is_sign_contract',3)
            ->where('is_send_return_order','!=',2)
            ->count();
            //取回中
            $returning_car = CarOrder::query()
            ->where('status',5)
            ->where('is_sign_contract',3)
            ->where('return_employer_id','!=',0)
            ->count();
            $history_order = CarOrder::query()->where('status',6)->where('process_status',6)->count();
            //待结算订单
            $waitting_settle = CarOrder::query()->where('status',6)->where('process_status',3)->count();
            //已取消订单
            $cancel_order = CarOrder::query()->whereIn('status',[-1,-2,-3])->count();
            //在租车车辆
            // $leased = CarOrder::query()->where('status',5)->count();
            //未结清
            $waitting_account = CarOrder::query()
                ->where('status',6)
                ->where(function($query){
                    $query->whereNotNull('unpaid')
                        ->orWhere('violation_unsettle')
                        ->orWhere('deposit_unsettle');
                })
                // ->whereNotNull('is_closed',1)
                ->whereIn('process_status',[4,5])
                ->count();
            // 租金未结清
            $unpaid_zj = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('unpaid','>',0)
            ->count();
            // 押金未结清
            $unpaid_yj = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('unpaid_yj','>',0)
            ->count();
            // 违章未结清
            $unpaid_wz = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('unpaid_wz','>',0)
            ->count();
            // 事故未结清
            $unpaid_sg = CarOrder::query()
            ->where('status',6)
            ->whereIn('process_status',[4,5])
            ->where('unpaid_sg','>',0)
            ->count();
            // 总店
            // $zdCount = $this->cuctomer(1);
            // $tuanCount = $this->cuctomer(2);
            // $bcCount = $this->cuctomer(3);
            // $lqCount = $this->cuctomer(4);
            //待送达
            $arravite = $this->carProccess(1);
            //待取回
            $refund = $this->carProccess(2);
            // 报销审核
            $reimburse_count = Reimburse::query()->where('is_month',1)->where('status',1)->count();
            // 外调车订单
            $wd_order = ExternalTransfer::query()->where('id','>',0)->count();
            // 黑名单数量
            // $hmd_num = BlackList::query()->whereNull('deleted_at')->count();
        }
         // 黑名单数量
         $hmd_num = BlackList::query()->whereNull('deleted_at')->count();
        // 根据门店列表，返回对应的门店客户数量
        $department_cuctomer_count = $this->cuctomer();
        //待确认改价数量
        $changePriceNum = $this->changePriceConfirm($request);
        //年检90天内的车辆数量
        //now-90 < x < now
        $motsExpire = $this->betweenNinty('mots_end',90);
        //保养90天内车辆数量
        $serviceExpire = $this->betweenNinty('service_end',90);
        //交强险45天内车辆
        $tciExpire = $this->betweenNinty('tci_end',45);
        //商业险45天
        $vciExpire = $this->betweenNinty('vci_end',45);

        //回车信息
        $refundMessage = $this->carProccess(2,null,2);
        $data = compact('waitting_account',
            'waitting_settle','changePriceNum',
            'perparatory','waitting_confirm',
            'waitting_lease','leased',
            'is_over','waitting_return',
            'history_order','over_time_return',
            'motsExpire','serviceExpire','tciExpire',
            'arravite','refund','refundMessage','vciExpire',
            'illegals_num1','illegals_num2','illegals_num3','illegals_num4','waitting_servicing_num','service_manage',
            'is_servincing_num',
            'department_cuctomer_count',
            'reimburse_count','cancel_order','waiting_car','waiting_sign','used_car','returning_car',
            'unpaid_zj','unpaid_yj','unpaid_wz','unpaid_sg','wd_order','hmd_num'
        );
        return $this->success($data);
    }
    public function indexkh(Request $request)
    {
        $user = $request->user();
        // 店长数据
        // if($user->post_id==2){
        //     // 黑名单数量
        //     $hmd_num = BlackList::query()->where('department_id',$user->department_id)->whereNull('deleted_at')->count();
        // }else{
        //     // 黑名单数量
        //     $hmd_num = BlackList::query()->whereNull('deleted_at')->count();
        // }
        $hmd_num = BlackList::query()->whereNull('deleted_at')->count();
        // 根据门店列表，返回对应的门店客户数量
        $department_cuctomer_count = $this->cuctomer();
        $data = compact('department_cuctomer_count','hmd_num');
        return $this->success($data);
    }
    public function indexcl(Request $request)
    {
        // 所有车系
        $all_series = Cache::remember('all_series',30, function () {
            return Car::query()
                ->where('status','!=','-1')
                ->count();
        });
        // 所有车辆
        $all_lease = Cache::remember('all_lease',30, function () {
            return RecognizeDrivingLicense::query()
                ->whereNull('deleted_at')
                ->count();
        });
        // 待租车辆
        $waitting_lease = Cache::remember('waitting_lease',30, function () {
            return RecognizeDrivingLicense::query()
                ->whereNull('deleted_at')
                ->where('is_used',0)
                ->where('status','!=','-1')
                ->count();
        });
        // 处置车辆
        $delete_lease = Cache::remember('delete_lease',30, function () {
            return RecognizeDrivingLicense::query()
                ->onlyTrashed()
                ->count();
        });
        $data = compact('all_series','all_lease','waitting_lease','delete_lease');
        return $this->success($data);
    }
    public function indexwb(Request $request)
    {
        // 自己维修
        $wx_num2 =  Service::query()->where('is_custom',2)->where('status','!=',4)->count();
        // 委外维修
        $wx_num3 =  Service::query()->where('is_custom',3)->where('status','!=',4)->count();
        // 事故维修
        $wx_num4 =  Service::query()->where('is_custom',4)->where('status','!=',4)->count();
        // 历史维修
        $wx_num =  Service::query()->where('status',4)->count();
        // 历史保养
        $by_num = Maintenance::query()->where('id','>',0)->count();
        //年检90天内的车辆数量
        //now-90 < x < now
        $motsExpire = $this->betweenNinty('mots_end',90);
        //保养90天内车辆数量
        $serviceExpire = $this->betweenNinty('service_end',90);
        //交强险45天内车辆
        $tciExpire = $this->betweenNinty('tci_end',45);
        //商业险45天
        $vciExpire = $this->betweenNinty('vci_end',45);
        //保险记录
        $bx_num = InsureLogs::query()->where('id','>',0)->count();
        // 待大保养
        $big_serving = DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_spark_plug_mileage-spark_plug_mileage) <= ?',[5000])->count();
        // 待保养
        $uzi_serving = DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_kilo_mileage-total_mileage) <= ?',[1000])->count();
        $data = compact('wx_num','wx_num2','wx_num3','wx_num4','by_num','motsExpire','serviceExpire','tciExpire','vciExpire','bx_num','big_serving','uzi_serving');
        return $this->success($data);
    }
    public function indexcw(Request $request)
    {
        $user = $request->user();
        // 店长数据
        if($user->post_id==2){
            // 报销审核
            $reimburse_count = Reimburse::query()->where('status',1)->where('is_month',1)->where('department',$user->department_id)->count();
            // 已完成
            $reimburse_end = Reimburse::query()->where('status',4)->where('is_month',1)->where('department',$user->department_id)->count();
            // 月结
            $reimburse_month = Reimburse::query()->where('is_month',2)->where('department',$user->department_id)->count();
            // 未对账订单数量
            $nodz_total_dd =  CarOrder::query()->where('department',$user->department_id)->where('status',6)->whereIn('process_status',[4,5,6])->whereIn('is_reconciliation',[1,2])->count();
            $nodz_total_wd = DB::table('external_transfers')->where('department_id',$user->department_id)->whereIn('is_reconciliation',[1,2])->count();
            // 本月
            $start = Carbon::now()->month;
            $startYear = Carbon::now()->year;
            $startMonth = Carbon::create($startYear, $start, 1)->startOfMonth();
            $endMonth = Carbon::create($startYear, $start, 1)->endOfMonth();
            // 本月数据
            $this_model = CarOrder::query()->where('department',$user->department_id)->whereBetween('updated_at',[$startMonth,$endMonth])->where('status',6)->whereIn('process_status',[4,5,6])->whereIn('is_reconciliation',[3]);
            $this_model_wd =  DB::table('external_transfers')->where('department_id',$user->department_id)->whereBetween('updated_at',[$startMonth,$endMonth])->whereIn('is_reconciliation',[3]);
            // 本月已对账数量
            $this_month_dz_total_dd = $this_model->count();
            $this_month_dz_total_wd = $this_model_wd->count();
            // 本月已对账金额
            $this_month_dz_amount_dd = $this_model->get()->sum('fact_pay');
            $this_month_dz_amount_wd = $this_model_wd->get()->sum('profit_price');
            $nodz_total = $nodz_total_dd+$nodz_total_wd;
            $this_month_dz_total = $this_month_dz_total_dd+$this_month_dz_total_wd;
            $this_month_dz_amount = round($this_month_dz_amount_dd+$this_month_dz_amount_wd, 2);
        }else{
            // 报销审核
            $reimburse_count = Reimburse::query()->where('status',1)->where('is_month',1)->count();
            // 已完成
            $reimburse_end = Reimburse::query()->where('status',4)->where('is_month',1)->count();
            // 月结
            $reimburse_month = Reimburse::query()->where('is_month',2)->count();
            // 未对账订单数量
            $nodz_total_dd =  CarOrder::query()->where('status',6)->whereIn('process_status',[4,5,6])->whereIn('is_reconciliation',[1,2])->count();
            $nodz_total_wd = DB::table('external_transfers')->whereIn('is_reconciliation',[1,2])->count();
            // 本月
            $start = Carbon::now()->month;
            $startYear = Carbon::now()->year;
            $startMonth = Carbon::create($startYear, $start, 1)->startOfMonth();
            $endMonth = Carbon::create($startYear, $start, 1)->endOfMonth();
            // 本月数据
            $this_model = CarOrder::query()->whereBetween('updated_at',[$startMonth,$endMonth])->where('status',6)->whereIn('process_status',[4,5,6])->whereIn('is_reconciliation',[3]);
            $this_model_wd =  DB::table('external_transfers')->whereBetween('updated_at',[$startMonth,$endMonth])->whereIn('is_reconciliation',[3]);
            // 本月已对账数量
            $this_month_dz_total_dd = $this_model->count();
            $this_month_dz_total_wd = $this_model_wd->count();
            // 本月已对账金额
            $this_month_dz_amount_dd = $this_model->get()->sum('fact_pay');
            $this_month_dz_amount_wd = $this_model_wd->get()->sum('profit_price');
            $nodz_total = $nodz_total_dd+$nodz_total_wd;
            $this_month_dz_total = $this_month_dz_total_dd+$this_month_dz_total_wd;
            $this_month_dz_amount = round($this_month_dz_amount_dd+$this_month_dz_amount_wd, 2);
        }
        $data = compact('reimburse_count','reimburse_end','reimburse_month','nodz_total','this_month_dz_total','this_month_dz_amount');
        return $this->success($data);
    }
    protected function carProccess($status,$user=null,$type=null){
        $res =  CarOrder::query()->where('process_status',$status)->where('status','>',0);
        if($type==1){
            $res = $res->where('department',$user->department_id);
        }
        if($type==2){
            $res = $res->where('is_sign_contract',3)->where('return_employer_id',0); // 回车信息
        }elseif($status==2){
            $res = $res->where('is_send_return_order',2)->where('is_sign_contract',3)->where('return_employer_id',0); // 待取回是已发送取车单和已签署合同并且没接单取车单的
        }

        $res = $res->count();
        if($res){
            return $res;
        }else{
            return 0;
        }
    }
    protected function carStatus($status){
        $res =  RecognizeDrivingLicense::query()->whereNull('deleted_at')->where('status',$status)->count();
        if($res){
            return $res;
        }else{
            return 0;
        }
    }
    protected function betweenNinty($continue,$day){
        $res =  RecognizeDrivingLicense::query()->whereNull('deleted_at')->where($continue,'<',now()->addDays($day))->orWhereNull($continue)->count();
        if($res){
            return $res;
        }else{
            return 0;
        }
    }
    //获取客户数量
    public function cuctomer(){
        return Customer::query()->select(DB::raw('count(*) as user_count, department_id'))->where('is_black',0)->groupBy('department_id')->get();
    }
    //获取某月新增客户数量
    public function cuctomerByMonth(Request $request){
        // 本月
        $start = $request->input('month',Carbon::now()->month);
        $startYear = $request->input('year',Carbon::now()->year);
        $startMonth = Carbon::create($startYear, $start, 1)->startOfMonth();
        $endMonth = Carbon::create($startYear, $start, 1)->endOfMonth();
        // 上月
        $laststart = $request->input('last_month',Carbon::now()->month);
        $laststartYear = $request->input('last_year',Carbon::now()->year);
        $laststartMonth = Carbon::create($laststartYear, $laststart, 1)->startOfMonth();
        $lastendMonth = Carbon::create($laststartYear, $laststart, 1)->endOfMonth();
        // 统计
        $startMonthData = Customer::query()->whereBetween('created_at',[$startMonth,$endMonth])->select(DB::raw('count(*) as user_count, department_id'))->where('is_black',0)->groupBy('department_id')->get();
        $lastMonthData = Customer::query()->whereBetween('created_at',[$laststartMonth,$lastendMonth])->select(DB::raw('count(*) as user_count, department_id'))->where('is_black',0)->groupBy('department_id')->get();
        return $this->success(compact('startMonthData','lastMonthData'));
    }
    //改价确认
    private function changePriceConfirm($request){
        $user = $request->user();
        $department = $user->department_id;
        // 当前部门基础信息
        $hasId = [];
        $departmentlist = Department::query()->get();
        foreach($departmentlist as $item){
            $change_price_notify = $item->change_price_notify;
            if(in_array($department, $change_price_notify)){
                $hasId[] = $item->id;
            }
        }
        if($user->post_id==2){
            // 店长根据配置，查自己能看的数据
            if (count($hasId) > 0) {
                $num = CarOrder::query()->where('confirm_change_price',1)->whereIn('department',$hasId)->count();
            } else {
                $num = 0;
            }
       } else {
            // 管理可以看全部
            $num = CarOrder::query()->where('confirm_change_price',1)->count();
       }
        // switch ($department){
        //     case 1://总店
        //         $num = CarOrder::query()
        //             ->where('department',$department)
        //             ->where('confirm_change_price',1)->count();
        //         break;
        //     case 2://途安店
        //         $num = CarOrder::query()
        //             ->whereIn('department',[3,4])
        //             ->where('confirm_change_price',1)->count();
        //         break;
        //     case 3://贝村店
        //         $num = CarOrder::query()
        //             ->where('department',2)
        //             ->where('confirm_change_price',1)->count();
        //         break;
        //     case 4://柳青店
        //         $num = 0;
        //         break;
        //     default:
        //         $num = 0;
        //         break;
        // }
        return $num;
    }

    protected function getCategoryNum($category,$request){
        $model = RecognizeDrivingLicense::query()
            ->whereNull('deleted_at')
            ->where('category',$category);
        if($request->filled('limit')&&$request->limit=='all'){
                return $model->count('id');
        }
        if($request->filled('status')){
            $model = $model->where('status',$request->status);
        }
        if($request->filled('use_status')&&$request->use_status == 2){
            $model = $model->where(function ($query) use($request) {
                $query->where('use_status',2)->orWhere('repair_status','!=',1);
            });
        }
        if($request->filled('is_used')){
            // 如果是查询的待租车辆，需要去订单里取出所有待送达和待取回车辆，租期之外的在租车辆也需要返回给前端使用能出车的
            $model = $model->where('status','!=','-1');
            if($request->filled('start')&&$request->is_used==0){
                // 先取出所有在租的车辆ID
                $usedCarLists = RecognizeDrivingLicense::query()->whereNull('deleted_at')->where('is_used', 1)->pluck('id');
                // $usedCarLists = $usedCarLists->unique(); // 去重
                // info('$usedCarLists:'.$usedCarLists);
                // $testssss = CarOrder::query()->where('status',5)->whereIn('process_status',[1,2])->where('pre_return_time','<',$request->start)->whereIn('gear_car_id',$usedCarLists)->get();
                // info('$testssss:'.$testssss);
                // 取出所有在租订单（待送达和待取回）
                $usedCars = [];
                $usedCarsAll = [];
                $usedOrders = CarOrder::query()->where('status',5)->whereIn('process_status',[1,2])->whereIn('gear_car_id',$usedCarLists)->get();//->pluck('gear_car_id');
                // 把所有订单的车辆ID和预取回存在字段里
                foreach ($usedOrders as $orderitem){
                    $columnValues = array_column($usedCarsAll, 'gear_car_id'); // 获取所有的值
                    $keys = array_search($orderitem->gear_car_id, $columnValues);
                    if($keys !== false){
                        $usedCarsAll[$keys]['timelist'][] = $orderitem->pre_return_time;
                    }else{
                        $usedCarsAll[] = [
                            'gear_car_id'=>$orderitem->gear_car_id,
                            'timelist'=>[$orderitem->pre_return_time]
                        ];
                    }
                }
                // info($usedCarsAll);
                // 反转数据，只保留重复项的最后一个
                // $usedCarsAllRes = array_reverse($usedCarsAll);
                // $usedCarsSingle = $this->array_unique_by_value($usedCarsAllRes,'gear_car_id');
                foreach ($usedCarsAll as $caritem){
                    // 取时间判断
                    if($this->array_is_all_out($caritem['timelist'],$request->start)){
                        $usedCars[] = $caritem['gear_car_id'];
                    }
                }
                // info($usedCarsSingle);
                // $usedCars = $usedCars->unique(); // 去重
                // info('$usedCars:'.json_encode($usedCars));
                if(count($usedCars)>0){
                    // info($usedCars);
                    $model = $model->where(function ($query) use($usedCars) {
                        $query->where('is_used',0)->orWhereIn('id',$usedCars);
                    });
                }else{
                    $model = $model->where('is_used',$request->is_used);
                }
            }else{
                $model = $model->where('is_used',$request->is_used);
            }
        }
        return $model->count('id');
    }
    // 判断某个值是否都在数组值之外（时间判断）
    protected function array_is_all_out($array, $values) {
        $isout = true;
        foreach ($array as $value) {
            // 只要有一个数组里的时间比比较值大，就false
            if (strtotime($value)>=strtotime($values)) {
                $isout = false;
            }
        }
        return $isout;
    }
    // php 数组根据某个值去重
    protected function array_unique_by_value($array, $key) {
        $unique = array();
        foreach ($array as $value) {
            if (!array_key_exists($key, $value)) {
                throw new InvalidArgumentException('The provided array does not have the specified key');
            }
            if (!array_key_exists($value[$key], $unique)) {
                $unique[$value[$key]] = $value;
            }
        }
        return array_values($unique);
    }
    protected function getCategoryCar($category,$is_used=null){
        $is_used = (int)$is_used;
        if($is_used == 1){
            return  RecognizeDrivingLicense::query()
                ->with('carSeries')
                ->whereNull('deleted_at')
                ->where('is_used',1)
                ->where('category',$category)->orderByDesc('id')->get();
        }elseif($is_used == 2){
            return  RecognizeDrivingLicense::query()
                ->with('carSeries')
                ->whereNull('deleted_at')
                ->where('is_used',0)
                ->where('category',$category)->orderByDesc('id')->get();
        }else{
            return  RecognizeDrivingLicense::query()
                ->with('carSeries')
                ->whereNull('deleted_at')
                ->where('category',$category)->orderByDesc('id')->get();
        }

    }

    public function getCarCategoryNum(Request $request){
        //新能源
        $new_energy = $this->getCategoryNum('新能源',$request);
        //经济型
        $economical = $this->getCategoryNum('经济型',$request);
        //豪华型
        $luxury = $this->getCategoryNum('豪华型',$request);
        //舒适型
        $comfortable = $this->getCategoryNum('舒适型',$request);
        //商务型
        $business = $this->getCategoryNum('商务型',$request);
        //越野型
        $off_road = $this->getCategoryNum('越野型',$request);
        return $this->success(compact('new_energy','economical','luxury','comfortable','business','off_road'));
    }
    protected function getCareriesNum($category){
        return Car::query()->where('category',$category)->where('status',1)->count();
    }
    //车系下车辆数量
    public function getCarSeriesCategoryNum(){
        //新能源
        $new_energy = $this->getCareriesNum('新能源');
        //经济型
        $economical = $this->getCareriesNum('经济型');
        //豪华型
        $luxury = $this->getCareriesNum('豪华型');
        //舒适型
        $comfortable = $this->getCareriesNum('舒适型');
        //商务型
        $business = $this->getCareriesNum('商务型');
        //越野型
        $off_road = $this->getCareriesNum('越野型');
        return $this->success(compact('new_energy','economical','luxury','comfortable','business','off_road'));
    }
    //获取车辆租期统计
    public function statisticsNum(Request $request){
        $user = $request->user();
        if($user->post_id==1){
            //今日收车
            $today = CarOrder::query()->whereBetween('pre_return_time',[Carbon::today(),Carbon::tomorrow()])->where("status",5)->count();
            //明日收车
            $tomorrow = CarOrder::query()->whereBetween('pre_return_time',[Carbon::tomorrow(),date('Y-m-d',strtotime(now()->addDays(2)))])->where("status",5)->count();
            //逾期
            $later = CarOrder::query()->where('pre_return_time','<',now())->where("status",5)->count();
            //收车
            $close_car = CarOrder::query()->where('status',6)
                ->where("process_status",0)
                ->where('openid','<>',"")
                ->count();

//        全部
            $all = CarOrder::query()->where("status",5)->count();
        }else{
            //今日收车
            $today = CarOrder::query()
                ->whereBetween('pre_return_time',[Carbon::today(),Carbon::tomorrow()])
                ->where("status",5)
                ->where('department',$user->department_id)
                ->count();
            //明日收车
            $tomorrow = CarOrder::query()
                ->whereBetween('pre_return_time',[Carbon::tomorrow(),date('Y-m-d',strtotime(now()->addDays(2)))])
                ->where("status",5)
                ->where('department',$user->department_id)
                ->count();
            //逾期
            $later = CarOrder::query()
                ->where('pre_return_time','<',now())
                ->where('department',$user->department_id)
                ->where("status",5)->count();
            //收车
            $close_car = CarOrder::query()->where('status',6)
                ->where('department',$user->department_id)
                ->where("process_status",0)
                ->where('openid','<>',"")
                ->count();

//        全部
            $all = CarOrder::query()
                ->where('department',$user->department_id)
                ->where("status",5)->count();
        }

        $data = compact('today','tomorrow','later','all','close_car');
        return $this->success($data);
    }

}
